<template>
  <div class="ui-cropper">
    <div class="cropper-imgs">
      <div class="ice-add-image-cropper-box-new">
        <div class="ice-add-image-cropper">
          <div class="ice-add-image-cropper-wrap">
            <img
              class="cropper-img"
              :src="cropperImg.url"
              :id="cropperImg.key"
              ref="img"
            />
          </div>
          <div class="ice-add-image-option">
            <div class="image-crop-type-box">
              <div class="image-crop-type-title">
                请选择合适的比例进行裁剪：
              </div>
              <div class="image-crop-type-btn-group">
                <div
                  class="crop-type-btn"
                  :class="
                    selectedCropType === btn.key ? 'crop-type-btn-selected' : ''
                  "
                  v-for="btn in cropTypeBtns"
                  :key="btn.key"
                  :data-i="cropperImg.i"
                  :data-key="btn.key"
                  :data-ratio="btn.ratio"
                  @click="onChangeCropType"
                >
                  <div class="crop-type-btn-inner" :class="btn.className">
                    {{ btn.name }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="iai-add-image__selectbar_new">
        <div class="iai-add-image__list">
          <div
            class="iai-add-image__selectbar-item"
            v-for="(img, i) in cropperImgs"
            :key="img.key"
            :data-i="i"
            :data-key="img.key"
            :data-ratiokey="img.ratioKey"
            :class="cropSelectbarKey === img.key ? 'selected' : ''"
            @click="onChangeCropSelect"
          >
            <div class="iai-add-image__selectbar-item-cover">
              <img :src="img.url" draggable="false" />
            </div>
          </div>
        </div>
      </div>
      <div class="ice-add-image-dialog-new__footer">
        <div class="ice-add-image-dialog-new__footer__limit"></div>
        <div class="ice-add-image-dialog-new__footer__operation">
          <Button
            type="primary"
            @click="onCropperExport"
            :disabled="!cropperImgs.length || !cropperReady"
            >确定</Button
          >
          <Button @click="onHide">取消</Button>
        </div>
      </div>
    </div>
    <div class="cropper-export" v-if="cropperExportView">
      <div
        class="cropper-export-item"
        v-for="img in cropperImgs"
        :key="img.key"
      >
        <img :src="img.url" class="cropper-img" :ref="`ci-${img.key}`" />
      </div>
    </div>
    <div class="cropper-anchor-view" v-if="cropperExportView">
      <div
        class="cropper-anchor-view--item"
        v-for="img in cropperExporImgs"
        :key="img.key"
      >
        <img
          :src="
            `${img.url}?x-oss-process=image/crop,x_${img.x},y_${img.y},w_${img.w},h_${img.h}`
          "
        />
      </div>
    </div>
  </div>
</template>

<script>
import Cropper from 'cropperjs'
const cropperOps = {
  viewMode: 1,
  dragMode: 'none',
  movable: false,
  rotatable: false,
  scalable: false,
  zoomable: false,
  zoomOnTouch: false,
  zoomOnWheel: false,
  minCropBoxWidth: 88,
  minCropBoxHeight: 88
  // checkCrossOrigin: false
}
export default {
  name: 'ui-cropper',
  props: {
    images: {
      type: Array,
      default() {
        return []
      }
    },
    CropType: {
      type: String,
      default() {
        return '00'
      }
    },
    minCropBoxWidth: {
      type: Number,
      default: 88
    },
    minCropBoxHeight: {
      type: Number,
      default: 88
    }
  },
  watch: {},
  data() {
    return {
      cropperExportView: false,
      cropper: null,
      cropperImg: {
        url: '',
        key: '',
        i: ''
      },
      cropperImgs: [],
      cropTypeBtns: [
        {
          key: '11',
          name: '1:1',
          ratio: 1 / 1,
          className: 'crop-type-1-1'
        },
        {
          key: '43',
          name: '4:3',
          ratio: 4 / 3,
          className: 'crop-type-4-3'
        },
      ],
      selectedCropType: '11',
      cropSelectbarKey: '',
      addAnchorModal: false,
      cropperExportImg: '',
      cropperExporImgs: [],
      cropperReady: false,

      minHeight: 0,
      minWidth: 0,
    }
  },
  mounted() {
    switch(this.CropType) {
      case '11':
          var startAspectRatio = 1 / 1
          var startRatioKey = '11'
          this.selectedCropType = '11'
          this.cropTypeBtns = [
            {
              key: '11',
              name: '1:1',
              ratio: 1 / 1,
              className: 'crop-type-1-1'
            }
          ]
        break;
      case '43':
          var startAspectRatio = 4 / 3
          var startRatioKey = '43'
          this.selectedCropType = '43'
          this.cropTypeBtns = [
            {
              key: '43',
              name: '4:3',
              ratio: 4 / 3,
              className: 'crop-type-4-3'
            }
          ]
        break;
      case '34':
          var startAspectRatio = 3 / 4
          var startRatioKey = '34'
          this.selectedCropType = '34'
          this.cropTypeBtns = [
            {
              key: '34',
              name: '3:4',
              ratio: 3 / 4,
              className: 'crop-type-3-4'
            }
          ]
        break;
      case '169':
          var startAspectRatio = 16 / 9
          var startRatioKey = '169'
          this.selectedCropType = '169'
          this.cropTypeBtns = [
            {
              key: '169',
              name: '16:9',
              ratio: 16 / 9,
              className: 'crop-type-16-9'
            }
          ]
        break;
      default:
          var startAspectRatio = 1 / 1
          var startRatioKey = '11'
          this.selectedCropType = '11'
    }
    this.cropperImgs = this.images.map((item, i) => ({
      ...item,
      aspectRatio: startAspectRatio,
      ratioKey: startRatioKey,
      cropperData: null,
      data: null,
      i
    }))
    this.cropperImg = this.cropperImgs[0]
    this.cropSelectbarKey = this.cropperImgs[0].key
    this.$nextTick(() => {
      this.initCropper(
        this.$refs.img,
        {
          aspectRatio: this.cropperImg.aspectRatio
        },
        {
          i: 0,
          aspectRatio: 1,
          ratioKey: '169'
        }
      )
    })
  },
  methods: {
    initMinCropper () {
      this.minHeight = this.minCropBoxHeight
      this.minWidth  = this.minCropBoxWidth
      const imgWidth  = this.images[0].imgw
      const imgHeight = this.images[0].imgh
      cropperOps.minCropBoxWidth  = (this.minCropBoxWidth / imgWidth)*300
      cropperOps.minCropBoxHeight = (this.minCropBoxHeight / imgHeight)*300
      // console.log('xxxxxxxxxxxx', cropperOps)
    },
    initCropper(ctx, initOps, initImgInfo) {
      this.initMinCropper()
      const cropper = new Cropper(ctx, {
        ...cropperOps,
        ready: () => {
          this.onUpdateCropperImgs(initImgInfo)
          this.cropperReady = true
        },
        cropend: () => {
          if (initImgInfo) {
            const { i, aspectRatio, ratioKey } = initImgInfo
            this.onUpdateCropperImgs({ i, aspectRatio, ratioKey })
          }
        },
        ...initOps
      })
      this.cropper = cropper
    },
    onUpdateCropperImgs({ i, aspectRatio, ratioKey }) {
      const cropperData = this.cropper.getCropBoxData()
      const data = this.cropper.getData()
      this.$set(this.cropperImgs, i, {
        ...this.cropperImgs[i],
        aspectRatio,
        cropperData,
        data,
        ratioKey
      })
    },
    onChangeCropType(e) {
      const { key, ratio, i } = e.currentTarget.dataset
      this.selectedCropType = key
      const initImgInfo = {
        i,
        aspectRatio: Number(ratio),
        ratioKey: key
      }
      this.cropper.destroy()
      this.cropperReady = false
      this.initCropper(
        this.$refs.img,
        {
          aspectRatio: Number(ratio),
          ready: () => {
            this.onUpdateCropperImgs(initImgInfo)
            this.cropperReady = true
          },
          cropend: () => {
            this.onUpdateCropperImgs(initImgInfo)
          }
        },
        initImgInfo
      )
    },
    onChangeCropSelect(e) {
      const { key, i, ratiokey } = e.currentTarget.dataset
      this.cropSelectbarKey = key
      this.selectedCropType = ratiokey
      this.cropperImg = this.cropperImgs[i]
      const ratio = this.cropperImg.aspectRatio
      const initImgInfo = {
        i,
        aspectRatio: Number(ratio),
        ratioKey: ratiokey
      }
      this.cropper.destroy()
      this.cropperReady = false
      this.$nextTick(() => {
        this.initCropper(this.$refs.img, {
          aspectRatio: this.cropperImg.aspectRatio,
          ready: () => {
            this.cropper.setCropBoxData(this.cropperImg.cropperData)
            this.onUpdateCropperImgs(initImgInfo)
            this.cropperReady = true
          },
          cropend: () => {
            // this.cropper.setCropBoxData(this.cropperImg.cropperData)
            this.onUpdateCropperImgs(initImgInfo)
          }
        })
      })
    },
    onCropperExport() {
      this.cropperExporImgs = this.cropperImgs.map(({ url, data, key }, i) => {
        let containerClassName = 'container-1-1'
        if (data) {
          const { x, y, width, height } = data
          const roundX = Math.round(x)
          const roundY = Math.round(y)
          const roundW = Math.round(width)
          const roundH = Math.round(height)
          if (width > height) {
            containerClassName = 'container-4-3'
          }

          if (width < height) {
            containerClassName = 'container-3-4'
          }
          return {
            i,
            url,
            key,
            x: roundX,
            y: roundY,
            w: roundW,
            h: roundH,
            containerClassName,
            anchor: null,
            anchorList: []
          }
        }
        return {
          i,
          url,
          key,
          x: 0,
          y: 0,
          w: 1440,
          h: 1440,
          containerClassName,
          anchor: null,
          anchorList: []
        }
      })

      const height = this.cropperExporImgs[0].h
      const width = this.cropperExporImgs[0].w
      if(this.minHeight > height) {
        this.$Message.info({
            content: '图片高度小于要求高度',
            duration: 6
        });
        return
      }
      if(this.minWidth > width) {
        this.$Message.info({
            content: '图片宽度小于要求宽度',
            duration: 6
        });
        return
      }
      
      // console.log('xxxxx此图片宽度xxxxx', width)
      // console.log('xxxxx此图片高度xxxxx', height)

      this.$emit('on-export', {
        images: this.cropperExporImgs
      })
      this.onHide()
    },
    onHide() {
      this.$emit('on-visible-change', false)
    },
    batchImgs() {
      this.initMinCropper()
      this.cropperImgs.forEach(item => {
        const cropper = new Cropper(this.$refs[`ci-${item.key}`][0], {
          ...cropperOps,
          aspectRatio: item.aspectRatio,
          ready() {
            const cropperData = this.cropper.getData()
            const canvas = this.cropper.getCroppedCanvas({
              maxWidth: 30,
              maxHeight: 30
            })
            canvas.toBlob(blob => {
              console.log({
                cropperData,
                [item.key]: blob
              })
              cropper.destroy()
            })
          }
        })
      })
    },
    getImageInfo(file) {
      return new Promise((resolve, reject) => {
        let filereader = new FileReader()
        filereader.onload = e => {
          let src = e.target.result
          const image = new Image()
          image.onload = () => {
            // const { width, height, src } = image
            resolve()
          }
          image.onerror = reject
          image.src = src
        }
        filereader.readAsDataURL(file)
      })
    }
  },
  destroyed() {
    // console.log('cropper ctx destroyed')
    this.cropperImgs = []
    this.cropperExporImgs = []
    this.cropperImg = {
      url: '',
      key: '',
      i: ''
    }
    this.selectedCropType = '11'
    this.cropSelectbarKey = ''
    this.cropper && this.cropper.destroy()
  }
}
</script>

<style lang="scss" scoped>
.cropper-img {
  max-width: 100%;
  max-height: 100%;
}
.ice-add-image-cropper {
  height: 300px;
  display: flex;
}
.ice-add-image-cropper-wrap {
  flex: 0 0 300px;
  height: 300px;
  text-align: center;
}
.image-crop-type-box {
  padding-left: 12px;
}
.image-crop-type-btn-group {
  display: flex;
  flex-wrap: wrap;
  .crop-type-btn {
    display: flex;
    & + .crop-type-btn {
      margin-left: 7px;
    }
    background-color: #e6e6e6;
    width: 32px;
    height: 32px;
    margin-bottom: 7px;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    &.crop-type-btn-selected {
      .crop-type-btn-inner {
        color: #6af;
        border-color: #6af;
      }
    }
  }
  .crop-type-btn-inner {
    color: #666;
    border: 1px solid #c7c7c7;
    background-color: rgba(255, 255, 255, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    width: 32px;
    height: 32px;
    font-size: 12px;
    &.crop-type-3-4 {
      width: 24px;
      height: 32px;
    }
    &.crop-type-4-3 {
      width: 32px;
      height: 24px;
    }
    &.crop-type-16-9 {
      width: 32px;
      height: 18px;
    }
  }
}
</style>
